﻿using System;
using System.Web.UI;

namespace U.Web
{
    /// <summary>
    /// 常见浏览器操作类，如获得安全的查询字符串，JS常用脚本等。
    /// </summary>
    public static class Browser
    {
        #region Query String

        public static string GetQueryString(string name, Page page)
        {
            var value = page.Request.QueryString[name];
            return value ?? string.Empty;
        }

        public static bool? GetBoolenQueryString(string name, Page page)
        {
            var value = GetQueryString(name, page);
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }
            bool result;
            return bool.TryParse(value, out result) ? (bool?) result : null;
        }

        public static int? GetIntQueryString(string name, Page page)
        {
            var value = GetQueryString(name, page);
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }
            int result;
            return int.TryParse(value, out result) ? (int?) result : null;
        }

        public static Guid? GetGuidQueryString(string name, Page page)
        {
            var value = GetQueryString(name, page);
            if (string.IsNullOrEmpty(value)) return null;
            try
            {
                var result = new Guid(value);
                return result;
            }
            catch
            {
                return null;
            }
        }

        #endregion

        #region JavaScript

        public static void Alert(string message, Page page)
        {
            Alert(message, "", page);
        }

        public static void Alert(string message, string extScript, Page page)
        {
            RunJS(string.Format("alert('{0}');{1}", message.Replace("'", "\\'"), extScript), page);
        }

        /// <summary>
        /// 执行自定义的JavaScript脚本
        /// </summary>
        /// <param name="script">脚本代码，不需要script标签</param>
        /// <param name="page">页面Page对象</param>
        public static void RunJS(string script, Page page)
        {
            var random = new Random();
            page.ClientScript.RegisterStartupScript(page.GetType(), "U_JS_" + random.Next(),
                                                    "<script language='javascript' defer>" + script + "</script>");
        }

        #endregion
    }
}